package com.zwy.springinner;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ChatClient1 {

    private static final String URL = "http://192.168.0.142:11434/api/chat"; // Ollama 的 API 地址
    private static final String MODEL = "deepseek-r1:1.5b"; // 使用的模型名称

    public static void main(String[] args) {
        List<JSONObject> messages = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("Chat client started. Type 'exit' to quit.");

            while (true) {
                System.out.print("You: ");
                String userInput = reader.readLine();

                if ("exit".equalsIgnoreCase(userInput)) {
                    System.out.println("Exiting chat client.");
                    break;
                }

                // 添加用户消息到消息列表
                JSONObject userMessage = JSONUtil.createObj()
                        .set("role", "user")
                        .set("content", userInput);
                messages.add(userMessage);

                // 创建 Ollama 的 JSON 请求体
                JSONObject jsonPayload = JSONUtil.createObj()
                        .set("model", MODEL)
                        .set("messages", messages)
                        .set("stream", false); // 设置为 false 以获取完整响应

                // 发送 POST 请求
                HttpResponse response = HttpRequest.post(URL)
                        .header("Content-Type", "application/json")
                        .body(jsonPayload.toString())
                        .execute();

                if (response.isOk()) {
                    String responseBody = response.body();
                    JSONObject jsonResponse = JSONUtil.parseObj(responseBody);

                    // 解析 Ollama 的响应
                    String assistantReply = jsonResponse.getByPath("message.content", String.class);
                    System.out.println("Assistant: " + assistantReply);

                    // 添加助手的回复到消息列表以保持上下文
                    JSONObject assistantMessage = JSONUtil.createObj()
                            .set("role", "assistant")
                            .set("content", assistantReply);
                    messages.add(assistantMessage);
                } else {
                    System.out.println("Request failed with status code: " + response.getStatus());
                    System.out.println("Response body: " + response.body());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
